package ru.inspirit.net
{
	import com.adobe.images.JPGEncoder;
	
	import flash.display.BitmapData;
	import flash.events.Event;
	import flash.net.URLLoader;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;
	
	public class JPGFileUploader {
		private static const UPLOADHOST: String = 'http://imagepost.ru';
		private static const DISTANCEURL: String = UPLOADHOST + '/images/';
		
		protected static function getSubStr(str: String, startStr: String, endString: String): String {
			var index: int = str.indexOf(startStr);
			if (index) {
				var eindex: int = index + startStr.length;
				return str.substr(eindex, str.indexOf(endString, eindex) - eindex);
			}
			return '';
		}

		protected static function uploadAsJPG(bmd: BitmapData, postkey: String, fileName: String, doUpload: Function, quality: uint=80): void {
			var jpe: JPGEncoder = new JPGEncoder(quality);
			var jpgData: ByteArray = jpe.encode(bmd);
			
			var mpl: MultipartURLLoader = new MultipartURLLoader();
			mpl.addFile(jpgData, fileName, "fileup", 'image/jpeg');
			mpl.addVariable('postkey', postkey);
			mpl.addEventListener(Event.COMPLETE, doUpload);
			mpl.load(UPLOADHOST);
		}
		
		public static function uploadBitmapData(bmd: BitmapData, fileName: String, doUpload: Function): void {
			var _loader: URLLoader = new URLLoader(new URLRequest('http://imagepost.ru'));
			_loader.addEventListener(Event.COMPLETE, function(e: Event): void {
				var html: String = (e.target.data as String);
				var postkey: String =getSubStr(html, 'id="postkey" value="', '"');
				if (postkey) {
					uploadAsJPG(bmd, postkey, fileName, function(e: Event): void {
						var fileURL: String = getSubStr(e.target.loader.data, '[img]' + DISTANCEURL, '[/img]');
						doUpload(DISTANCEURL + fileURL);
					});
				}				
			});
		}
	}
}